﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BusinessObjects;
using DataObjects.EntityFramework.ModelMapper;
using System.Linq.Dynamic;

namespace DataObjects.EntityFramework.Implementation
{
    public class EntityCountryDao : ICountryDao
    {
        public Country GetCountry(int CountryId)
        {
            using (var context = DataObjectFactory.CreateContext())
            {
                return Mapper.Map(context.CountryEntities.FirstOrDefault(c => c.CountryId == CountryId));
            }
        }
        public List<Country> GetCountries(string sortExpression = "CountryId ASC")
        {
            using (var context = DataObjectFactory.CreateContext())
            {
                var list = new List<Country>();

                var countries = context.CountryEntities.AsQueryable().OrderBy(sortExpression).ToList();
                foreach (var country in countries)
                    list.Add(Mapper.Map(country));

                return list;
            }
        }
        public void InsertCountry(Country country)
        {
            var entity = Mapper.Map(country);

            using (var context = DataObjectFactory.CreateContext())
            {
                context.CountryEntities.AddObject(entity);
                context.SaveChanges();

                // update business object with new version and id
                country.CountryId = entity.CountryId;

                //country.Version = Convert.ToBase64String(entity.Version);
            }
        }
        public void UpdateCountry(Country country)
        {
            using (var context = DataObjectFactory.CreateContext())
            {
                var entity = context.CountryEntities.Where(c => c.CountryId == country.CountryId).SingleOrDefault();

                entity.CountryId = country.CountryId;
                entity.CountryName = country.CountryName;

                context.CountryEntities.ApplyCurrentValues(entity);
                context.SaveChanges();

                // Update business object with new version
                //country.Version = Convert.ToBase64String(entity.Version);
            }
        }
        public void DeleteCountry(Country country)
        {
            using (var context = DataObjectFactory.CreateContext())
            {
                var entity = context.CountryEntities.Where(c => c.CountryId == country.CountryId).SingleOrDefault();
                context.CountryEntities.DeleteObject(entity);
                context.SaveChanges();
            }
        }
    }
}
